<template>
  <div class="loginPage">
    <el-card class="loginCard" shadow="always" :body-style="{ padding: '0px' }">
      <div class="box">
        <el-image :src="url" class="bgImg" />
        <div class="right">
          <h2 style="text-align: center">登录</h2>
          <el-form
            ref="formRef"
            label-width="100px"
            :model="ruleForm"
            :rules="rules"
            style="max-width: 460px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                show-password
                v-model="ruleForm.password"
              />
            </el-form-item>
            <el-form-item label="验证码" prop="verifyCode" v-if="codeOrPic">
              <div style="display: flex; height: 32px">
                <el-input v-model="ruleForm.verifyCode" />
                <div @click="getVerfication" style="margin-left: 8px">
                  <VerificationCode :identifyCode="identifyCode" />
                </div>
              </div>
            </el-form-item>
          </el-form>
          <div v-if="!codeOrPic" class="verifyPic">
            <VerificationPic
              @setVerifyCode="setVerifyCode"
              :picDisabled="picDisabled"
            />
          </div>

          <el-button
            type="primary"
            class="submitBtn"
            @click="submitForm(formRef)"
          >
            登录
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import router from "@/router"
import img from '@/assets/13.png'
import { onMounted, onUnmounted, reactive, ref } from "vue"
import api from 'Api/login';
import { setToken, setUserInfo } from 'Utils/cookies.js'
import VerificationCode from 'Components/VerificationCode/VerificationCode.vue';
import VerificationPic from 'Components/VerificationPic/VerificationPic.vue';
import { ElMessage as message } from "element-plus";

const formRef = ref()
const identifyCode = ref('12345')

const ruleForm = reactive({
  username: '',
  password: '',
  verifyCode: '',
})

const codeOrPic = ref(Math.floor(Math.random() * 10) > 5);
const picDisabled = ref(false)
//本地验证码方法
const getVerfication = () => {
  let res = ''
  for (let i = 0; i < 5; i++) {
    res += randomVerfyCode()
  }
  identifyCode.value = res
}
//验证码刷新方法
const randomVerfyCode = () => {
  let identifyCodes = "1234567890abcdefjhijklinopqrsduvwxyz";
  let Code = identifyCodes.split('');
  return Code[Math.floor(Math.random() * identifyCodes.length)]
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度3-10', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度6-18', trigger: 'blur' },
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
}

const submitForm = async (form) => {
  if (!form) {
    return;
  }
  await form.validate(async (valid) => {
    if (valid) {
      if (ruleForm.verifyCode !== identifyCode.value) {
        if (codeOrPic.value) {
          message.error('验证码错误')
          ruleForm.verifyCode = '';
        } else {
          message.error('滑块未验证')
          ruleForm.verifyCode = '';
        }
        getVerfication()
        return
      }
      let res = await api.login(ruleForm);
      if (res.status === true) {
        setUserInfo(res.data)
        setToken(res.data.token);
        router.push('/home');
      } else {
        //失败时重新调用验证码
        getVerfication()
        setVerifyCode(false)
        picDisabled.value = false;
      }
    } else {
      return false
    }
  })
}

const runTo = () => {
  router.push('/home')
}

const url = img;

const setVerifyCode = (type) => {
  if (type) {
    ruleForm.verifyCode = identifyCode.value;
    picDisabled.value = true;
  } else {
    ruleForm.verifyCode = '';
  }
}

const onEnter = (e) => {
  if (e.keyCode === 13) {
    submitForm(formRef.value)
  }
}

onMounted(() => {
  window.addEventListener('keydown', onEnter, false)
})

onUnmounted(() => {
  window.removeEventListener('keydown', onEnter, false)
})

</script>

<style lang="less" scoped>
@import url("./login.less");
</style>